import { getCurrentInstance } from "vue";
import { ApiLogin, ApiCheckCode } from '@/apis/user'
import { useRouter } from 'vue-router'
import { useStore } from '@/store/index'
interface LoginParm {
    username: string,
    password: string,
    code: string
}
//表单验证
export function useLogin(loginModel?: LoginParm) {
    const { proxy } = getCurrentInstance() as any;
    const router = useRouter();
    const store = useStore();

    const login = async () => {
        proxy.$refs.loginFormRef.validate(async (valid: boolean) => {
            if (valid && loginModel !== undefined) {
                if (await ApiCheckCode(loginModel) && await ApiLogin(loginModel)) {
                    store.commit('setAquarium', sessionStorage.getItem('aquarium'))
                    router.push({ path: 'home' })
                }
            }
        })
    }
    return {
        login
    }
}

export function useAutoLogin() {
    const autoLogin = async () => {
        const router = useRouter();
        const store = useStore();
        if (await ApiLogin()) {
            store.commit('setAquarium', sessionStorage.getItem('aquarium'))
        }
    }
    return {
        autoLogin
    }
}

//这是跳转的
export function useToRegister() {
    const router = useRouter();
    const toRegister = async () => {
        router.push({ path: 'register' })
    }
    return {
        toRegister
    }
}